package org.hiucung.hlsdownloader.utils

import android.os.Build
import androidx.annotation.RequiresApi
import org.hiucung.hlsdownloader.bean.EncryptionKey
import java.io.File
import java.net.URL
import java.util.Base64

/**
 * @title: M3U8KeyLoader
 * @projectName HLS Downloader
 * @description: M3U8 key解析
 * @author Kicc
 * @date 2025/8/23 15:09
 */
object M3U8KeyLoader {
    /**
     * 从URI加载加密key
     */
    fun loadKey(encryptionKey: EncryptionKey): ByteArray? {
        return try {
            when {
                encryptionKey.uri?.startsWith("http://") == true ||
                        encryptionKey.uri?.startsWith("https://") == true -> {
                    // 从网络加载
                    URL(encryptionKey.uri).openStream().use { it.readBytes() }
                }
                encryptionKey.uri?.startsWith("file://") == true -> {
                    // 从文件加载
                    File(encryptionKey.uri.substringAfter("file://")).readBytes()
                }
                encryptionKey.uri != null -> {
                    // 从本地文件加载
                    File(encryptionKey.uri).readBytes()
                }
                else -> null
            }
        } catch (e: Exception) {
            null
        }
    }

    /**
     * 从base64编码的URI加载key
     */
    @RequiresApi(Build.VERSION_CODES.O)
    fun loadKeyFromBase64Uri(encryptionKey: EncryptionKey): ByteArray? {
        return encryptionKey.uri?.let { uri ->
            if (uri.startsWith("data:application/octet-stream;base64,")) {
                val base64Data = uri.substringAfter("base64,")
                Base64.getDecoder().decode(base64Data)
            } else {
                null
            }
        }
    }
}